﻿using System;
using System.Text;
using System.IO;

namespace Steganograf
{
    class BmpOrigFile
    {
		private string m_fileName;

        public BmpOrigFile(string fileName)
        {
            this.m_fileName = fileName;
		}

        public BmpStegoFile CreateStegoFile(string pMessage, string pPassword)
        {
            using (FileStream inStream = new FileStream(m_fileName, FileMode.Open, FileAccess.Read)) 
            {
                char b = (char)inStream.ReadByte();
                char m = (char)inStream.ReadByte();
                if (!(b == 'B' && m == 'M'))
                    throw new Exception("Wybrany plik nie jest bitmapą!");

                byte[] buffer = new byte[2];
                inStream.Seek(28, 0);
                inStream.Read(buffer, 0, 2);
                Int16 nBit = BitConverter.ToInt16(buffer, 0);
                if (nBit != 24)
                    throw new Exception("Wybrany plik nie jest 24-bitową bitmapą!");

                /* Encrypt the message, read its length */
                byte[] messageBytes = (new UTF8Encoding()).GetBytes(Crypto.EncryptAes(pMessage, pPassword));
                byte[] length = GetMessageLength(messageBytes);

                /* Encode the source file using the LSB method */
                byte[] fileWithMessageHidden = null;
                try
                {
                    fileWithMessageHidden = LsbHelper.Encode(inStream, messageBytes, length, pPassword);
                }
                catch
                {
                    throw;
                }

                return new BmpStegoFile(fileWithMessageHidden);
            }
        }

        private byte[] GetMessageLength(byte[] pMsgBytes)
        {
            int length = pMsgBytes.Length; //*Redundancy.CODE_LENGTH;
            return BitConverter.GetBytes(length); //reads 32-bit integer -> always 4 bytes
        }
    }
}
